package com.android.server.actionHandler;

import java.io.IOException;
import java.util.Hashtable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ActionMappingParser {
	private Hashtable<String, String> mapping;
	
	public static final String ACTION_NODENAME_MAPPING = "mapping";
	public static final String ACTION_NODENAME_KEY = "event";
	public static final String ACTION_NODENAME_VALUE = "action-handler";
	public static final String MAPPING_FILE = "/conf/actionMapping.xml";
	
	public Hashtable<String, String> getMapping(){
		mapping = new Hashtable<String, String>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	    try {
	    	DocumentBuilder mBuilder = factory.newDocumentBuilder();
	    	Document doc = mBuilder.parse(ActionHandlerFactory.class.getResourceAsStream(MAPPING_FILE));
	    	NodeList nodes = doc.getChildNodes();
	    	getSettingNode(nodes);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mapping;
	}
	
	private void getSettingNode(NodeList nodes) throws JSONException {
		if(nodes == null){
			return;
		}
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if(node.getNodeName().equalsIgnoreCase(ACTION_NODENAME_MAPPING)){
				parserNode(node);
			}else{
				getSettingNode(node.getChildNodes());
			}
		}
	}
	
	private void parserNode(Node node) {
		if(node.getNodeName().equalsIgnoreCase(ACTION_NODENAME_MAPPING)){
			NodeList childNodes = node.getChildNodes();
			String action = null;
			String handler = null;
			for(int i = 0 ; i < childNodes.getLength() ; i++){
	    		Node childNode = childNodes.item(i);
	    		if(childNode.getNodeName().equalsIgnoreCase(ACTION_NODENAME_KEY)){
	    			action = childNode.getTextContent();
	    		}else if(childNode.getNodeName().equalsIgnoreCase(ACTION_NODENAME_VALUE)){
	    			handler = childNode.getTextContent();
	    		}
	    	}
			if(action != null && handler != null){
				mapping.put(action, handler);
			}
		}
	}
	
	public static void main(String[] args) {
		ActionMappingParser parser = new ActionMappingParser();
		Hashtable<String, String> a = parser.getMapping();
		System.out.println(a);
	}
}
